package com.wx.proxy.cglib;

import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib 测试
 *
 * @description:
 * @author: wangxun
 * @createDate: 2021/12/27
 * @version: 1.0
 */
@Slf4j
public class CglibTest {



    /**
     * 获取代理类
     *
     * @param cls
     * @return T
     * @author Wang.xun
     * @date 2021/12/27 16:33
     */
    <T> T getPoxy(Class<T> cls) {
        // Enhancer 增强剂
        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(cls);
        enhancer.setCallback(new MyInterceptor());
        return (T) enhancer.create();
    }

    // 自定义拦截器
    class MyInterceptor implements MethodInterceptor {

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            log.info("拦截器启动 方法名:{}",method.getName());
            // 被代理的类，实际操作
            Object rs  = proxy.invokeSuper(obj, args);

            log.info("拦截器结束");

            return rs;
        }
    }

    public static void main(String[] args) {
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E:\\cglibProxyClass");
        CglibTest cglibTest = new CglibTest();
        SayHello testPoxy = cglibTest.getPoxy(SayHello.class);
        testPoxy.hi();
    }
}
